package org.jash.shop2201.shop

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Route
import org.jash.shop2201.BR
import org.jash.shop2201.R
import org.jash.shop2201.databinding.FragmentCategoryBinding
import org.jash.shop2201.entity.Category
import org.jash.shop2201.entity.Goods
import org.jash.shop2201.mvvm.BaseFragment
import org.jash.shop2201.utils.CommonAdapter
import org.jash.shop2201.utils.Event

@Route(path = "/shop/category")
class CategoryFragment : BaseFragment<FragmentCategoryBinding, CategoryViewModel>() {
    val categoryAdapter by lazy { CommonAdapter<Category>({ R.layout.item_category to BR.category }) }
    val subcategoryAdapter by lazy { CommonAdapter<Category>({ R.layout.item_sub_category to BR.category }) }
    val goodsAdapter by lazy { CommonAdapter<Goods>({ R.layout.item_goods to BR.goods }) }
    override fun initData() {
        viewModel.categoryLiveData.observe(viewLifecycleOwner) {
            categoryAdapter += it
            it[0].showSubcategory()
        }
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            goodsAdapter.clear()
            goodsAdapter += it
        }
        viewModel.loadCategory()
    }

    override fun initView() {
        binding.category.adapter = categoryAdapter
        binding.subCategory.adapter = subcategoryAdapter
        binding.goods.adapter = goodsAdapter
    }
    @Event("展示子分类")
    fun loadSubcategory(list: List<Category>) {
        subcategoryAdapter.clear()
        subcategoryAdapter += list
        goodsAdapter.clear()
        if (list.isNotEmpty()) {
            list[0].showGoods()
        }
    }
    @Event("展示商品")
    fun loadGoods(cid:Int) {
        viewModel.loadGoods(cid, 1, 20)
    }
}